package cn.whb.hrm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class HrmAuthorticationConfig extends AuthorizationServerConfigurerAdapter{


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //对应/oauth/check_token ，路径公开
                .checkTokenAccess("permitAll()")
                //允许客户端进行表单身份验证,使用表单认证申请令牌
                .allowFormAuthenticationForClients();
    }


    @Autowired
    private DataSource dataSource;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用来配置客户端详情服务：
     * 如配置客户端id(client_id)资源id、
     * 客户端密钥(secrect)、
     * 授权方式、
     * scope等,可以基于内存或jdbc。
     * (可以理解为是对浏览器向授权服务器获取授权码或令牌时需要提交的参数配置)
     * @param clients
     * @throws Exception
     */
    //客户端详情：配置客户端请求的参数
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        JdbcClientDetailsService jdbcClientDetailsService = getJdbcClientDetailsService();
        clients.withClientDetails(jdbcClientDetailsService);
    }

    private JdbcClientDetailsService getJdbcClientDetailsService() {
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
        jdbcClientDetailsService.setPasswordEncoder(passwordEncoder);
        return jdbcClientDetailsService;
    }


    @Autowired
    private AuthenticationManager authenticationManager;
    /**
     * 配置令牌的访问端点url和令牌服务，
     * 如配置如何管理授权码(内存或jdbc)，
     * 如何管理令牌(存储方式，有效时间等等)
     * @param endpoints
     * @throws Exception
     */
    //授权服务端点：配置授权码和令牌的管理/存储方式
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //1.密码授权模式需要
                .authenticationManager(authenticationManager)
                //2.授权码模式服务
                .authorizationCodeServices(codeServices())
                //3.配置令牌管理服务
                .tokenServices(tokenService())  //将token放在内存中
                //允许post方式请求
                .allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET);
    }

    private AuthorizationCodeServices codeServices() {
        JdbcAuthorizationCodeServices services = new JdbcAuthorizationCodeServices(dataSource);
        return services;
    }

    private static final String key = "wanghongbin";

    @Bean
    public TokenStore tokenStore() {
        JwtAccessTokenConverter converter = getJwtAccessTokenConverter();
        return new JwtTokenStore(converter);
    }

    @Bean
    public JwtAccessTokenConverter getJwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(key);
        return converter;
    }

    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        //获取客户端详情
        tokenServices.setClientDetailsService(getJdbcClientDetailsService());
        //是否支持刷新
        tokenServices.setSupportRefreshToken(true);
        //指定存储方式
        tokenServices.setTokenStore(tokenStore());
        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(getJwtAccessTokenConverter()));
        tokenServices.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()
        return tokenServices;
    }
}
